package com.example.redistokendemo.utils;


import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * token的生成，以及校验
 *
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-11 20:28
 */
@Component
public class TokenUtil {

    @Autowired
    private RedisUtil redisUtil;

    private static final String TOKEN_NAME = "token";

    /**
     * 生成token放入Redis中并返回token
     *
     * @return
     */
    public String createToken() {
        String token = TOKEN_NAME.concat(RandomUtil.randomUUID().replaceAll("-", ""));
        //有效期1小时
        redisUtil.set(token, token, 60 * 60);
        return token;
    }

    /**
     * 校验参数并删除token
     *
     * @param request
     */
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isEmpty(token)) {
                throw new IllegalArgumentException("接口缺少token！");
            }
        }
        if (!redisUtil.del(token)) {
            throw new IllegalArgumentException("请勿重复提交！");
        }
    }

}
